package com.github.postsanf.yinian.activity;

import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.github.postsanf.yinian.BaseActivity;
import com.github.postsanf.yinian.R;
import com.github.postsanf.yinian.bean.YNAddress;
import com.github.postsanf.yinian.constants.ACTIONs;
import com.github.postsanf.yinian.constants.CommonConstants;
import com.github.postsanf.yinian.utils.StringUtils;
import com.github.postsanf.yinian.widget.CityPicker;
import com.litesuits.http.exception.HttpException;
import com.litesuits.http.listener.HttpListener;
import com.litesuits.http.request.StringRequest;
import com.litesuits.http.request.param.HttpMethods;
import com.litesuits.http.response.Response;
import com.umeng.analytics.MobclickAgent;

import org.json.JSONObject;

import java.util.LinkedHashMap;

public class ShopAddressEditActivity extends BaseActivity implements View.OnClickListener {
    private EditText order_name;
    private EditText order_telphone;
    private EditText order_address;
    private LinearLayout order_select_city;
    private TextView order_city_tx;
    private Dialog saddressDialog;
    private String Pickerprovince;
    private String Pickercity;
    private String Pickerarea;
    private String addressID;
    private String type;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_receiveraddressedit);
        initView();
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.addressedit_back:
                finish();
                break;
            case R.id.order_select_city:
                if (!saddressDialog.isShowing()) {
                    saddressDialog.show();
                }
                break;
            case R.id.addressedit_next:
                doNext();
                break;
        }
    }

    private void initView() {
        if (getIntent() != null && getIntent().getStringExtra("type") != null) {
            type = getIntent().getStringExtra("type");
        } else {
            type = "add";
        }
        findViewById(R.id.addressedit_back).setOnClickListener(this);
        findViewById(R.id.addressedit_next).setOnClickListener(this);
        order_name = (EditText) findViewById(R.id.order_name);
        order_telphone = (EditText) findViewById(R.id.order_telphone);
        order_address = (EditText) findViewById(R.id.order_address);
        order_city_tx = (TextView) findViewById(R.id.order_city_tx);
        order_select_city = (LinearLayout) findViewById(R.id.order_select_city);
        order_select_city.setOnClickListener(this);
        RelativeLayout addressLayout = (RelativeLayout) LayoutInflater
                .from(ShopAddressEditActivity.this).inflate(
                        R.layout.show_citypicker_dialog, null);
        saddressDialog = new Dialog(
                ShopAddressEditActivity.this, R.style.dialog);
        saddressDialog.setContentView(addressLayout, new ViewGroup.LayoutParams(-2,
                -2));
        final CityPicker cityPicker = (CityPicker) addressLayout
                .findViewById(R.id.citypicker);
        addressLayout.findViewById(R.id.btn_ok).setOnClickListener(
                new View.OnClickListener() {
                    public void onClick(View v) {
                        Pickerprovince = cityPicker.getProvince();
                        Pickercity = cityPicker.getCity();
                        Pickerarea = cityPicker.getArea();
                        order_city_tx.setText(cityPicker.getCity_string());
                        saddressDialog.dismiss();
                    }
                });
        if (getIntent() != null && getIntent().getSerializableExtra("YNAddress") != null) {
            YNAddress ynAddress = (YNAddress) getIntent().getSerializableExtra("YNAddress");
            addressID = String.valueOf(ynAddress.getAddressID());
            order_name.setText(ynAddress.getAddressReceiver());
            order_telphone.setText(ynAddress.getAddressPhoneNumber());
            order_address.setText(ynAddress.getAddressDetail());
            Pickerprovince = ynAddress.getAddressProvince();
            Pickercity = ynAddress.getAddressCity();
            Pickerarea = ynAddress.getAddressArea();
            order_city_tx.setText(Pickerprovince + Pickercity + Pickerarea);
        }

    }

    private void doNext() {
        if (StringUtils.isEmpty(order_name.getText().toString())) {
            Toast.makeText(ShopAddressEditActivity.this, "收货人不能为空", Toast.LENGTH_SHORT).show();
            return;
        }
        if (StringUtils.isEmpty(order_telphone.getText().toString())) {
            Toast.makeText(ShopAddressEditActivity.this, "电话号码不能为空", Toast.LENGTH_SHORT).show();
            return;
        }
        if (StringUtils.isEmpty(order_city_tx.getText().toString())) {
            Toast.makeText(ShopAddressEditActivity.this, "请选择地区", Toast.LENGTH_SHORT).show();
            return;
        }
        if (StringUtils.isEmpty(order_address.getText().toString())) {
            Toast.makeText(ShopAddressEditActivity.this, "地址不能为空", Toast.LENGTH_SHORT).show();
            return;
        }
        EditAddressNext(type, addressID, order_name.getText().toString(),
                order_telphone.getText().toString(),
                Pickerprovince, Pickercity, Pickerarea,
                order_address.getText().toString());
    }

    private void EditAddressNext(String type, String edaddressID, String receiver,
                                 String phone,
                                 String province,
                                 String city,
                                 String area,
                                 String detail) {
        LinkedHashMap<String, String> mParam = new LinkedHashMap<>();
        mParam.put("userid", String.valueOf(application.getCurID()));
        mParam.put("type", type);
        if (!StringUtils.isEmpty(edaddressID)) {
            mParam.put("addressID", edaddressID);
        }
        mParam.put("receiver", receiver);
        mParam.put("phone", phone);
        mParam.put("province", province);
        mParam.put("city", city);
        mParam.put("area", area);
        mParam.put("detail", detail);
        StringRequest req = new StringRequest(getString(R.string.SHOP_URL) + getString(R.string.ynManageAddress))
                .setMethod(HttpMethods.Post)
                .setParamMap(mParam)
                .setHttpListener(new HttpListener<String>(true, false, true) {
                    @Override
                    public void onSuccess(String s, Response<String> response) {
                        try {
                            JSONObject jsonObject = new JSONObject(s.toString());
                            if (jsonObject.optString("msg").equals("success") && jsonObject.optInt("code") == 0) {
                                if (jsonObject.optJSONArray("data") != null) {
                                    String successaddressID = jsonObject.optJSONArray("data").optJSONObject(0).optString("addressID");
                                    addressID = successaddressID;
                                }
                                ChangeDefaultAddress(addressID);
                                showToast("成功");
                                sendBroadcast(new Intent(ACTIONs.actionUpdateShopAddressList));
                                finish();
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onFailure(HttpException e, Response<String> response) {
                        showToast(CommonConstants.YN_NET_LINK);
                    }
                });
        liteHttp.executeAsync(req);
    }

    private void ChangeDefaultAddress(String addressID) {
        LinkedHashMap<String, String> mParam = new LinkedHashMap<>();
        mParam.put("userid", String.valueOf(application.getCurID()));
        mParam.put("addressID", addressID);
        StringRequest req = new StringRequest(getString(R.string.SHOP_URL) + getString(R.string.ynChangeDefaultAddress))
                .setMethod(HttpMethods.Post)
                .setParamMap(mParam)
                .setHttpListener(new HttpListener<String>(true, false, true) {
                    @Override
                    public void onSuccess(String s, Response<String> response) {
                    }

                    @Override
                    public void onFailure(HttpException e, Response<String> response) {
                        showToast(CommonConstants.YN_NET_LINK);
                    }
                });
        liteHttp.executeAsync(req);
    }

    // 友盟统计
    public void onResume() {
        super.onResume();
        MobclickAgent.onPageStart(this.getClass().getSimpleName());
        MobclickAgent.onResume(this);
    }

    public void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd(this.getClass().getSimpleName());
        MobclickAgent.onPause(this);
    }

}
